'''tcp协议实现客户端输入的命令执行、将结果放到管道中、在管道中读取返回带客户端'''
'''TCP 协议实现：客户端发送命令’服务端接收命令并把命令执行后的结果发送给客户端、
从缓存区取数据时取的少了就出现粘包、下次取的还是上次烦的内容'''
import subprocess
from socket import *
ip_port = ("localhost", 51590)
buffer_size = 1024
back_log=5
tcp_server=socket(AF_INET,SOCK_STREAM)
tcp_server.bind(ip_port)
tcp_server.listen(back_log)
while True:
    print("waiting for connenct....")
    conn,addr=tcp_server.accept()
    print("双向链接是", conn)
    print("客户端地址", addr)
    while True:
        try:
            cmd = conn.recv(buffer_size)
            if not cmd:break
            print("收到客户端发送的消息是：",cmd)
            res = subprocess.Popen(cmd.decode("utf-8"),shell=True,
                             stderr=subprocess.PIPE,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE)
            err=res.stderr.read()
            if err:
                cmd_res=err
            else:
                cmd_res=res.stdout.read()
            if not cmd_res:
                cmd_res="执行成功".encode("gbk")
            conn.send(cmd_res)
        except Exception:
            print(Exception)
            break
    conn.close()